/* Copyright 2009 Sony Mathew, Minneapolis MN. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
package com.xsm.muck.binding;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.xsm.servlet.ServletBindingProvider;

/**
 * Configure Servlets with this binding provider so they can access our IoC Binding.
 * The Servlets are expected to cast the binding provided here to the IoC Context they have defined.
 * See example: RemoteEventProxyServlet
 *    
 * @author Sony Mathew
 */
public class MuckServerBindingProvider implements ServletBindingProvider {
    private static final String BINDING_KEY = MuckServerBinding.class.getName();
    
    /**
     * Provide an instance of the server-side binding for the Muck web app.
     * 
     * @see com.xsm.servlet.ServletBindingProvider#getServletBinding(javax.servlet.http.HttpServlet, javax.servlet.http.HttpServletRequest)
     */
    public Object getServletBinding(HttpServlet servlet, HttpServletRequest req) {
        try {
            HttpSession ses = req.getSession(true);
            Object binding = ses.getAttribute(BINDING_KEY);
            if (binding == null) {
                binding = new MuckServerBinding();
                ses.setAttribute(BINDING_KEY, binding);
            }        
            return binding;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    
}
